<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="标题" prop="title">
        <el-input v-model="queryParams.title" placeholder="请输入标题" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="分数" prop="score">
        <el-input v-model="queryParams.score" placeholder="请输入分数" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="类型" prop="type">
        <el-select v-model="queryParams.type" placeholder="请选择类型" clearable>
          <el-option v-for="dict in dict.type.question_type" :key="dict.value" :label="dict.label"
            :value="dict.value" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd"
          v-hasPermi="['exa:bank:add']">新增</el-button>
      </el-col>
      <!-- <el-col :span="1.5">
        <el-button type="success" plain icon="el-icon-edit" size="mini" :disabled="single" @click="handleUpdate"
          v-hasPermi="['exa:bank:edit']">修改</el-button>
      </el-col> -->
      <el-col :span="1.5">
        <el-button type="danger" plain icon="el-icon-delete" size="mini" :disabled="multiple" @click="handleDelete"
          v-hasPermi="['exa:bank:remove']">删除</el-button>
      </el-col>
      <!-- <el-col :span="1.5">
        <el-button type="warning" plain icon="el-icon-download" size="mini" @click="handleExport"
          v-hasPermi="['exa:bank:export']">导出</el-button>
      </el-col> -->
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="bankList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="ID" align="center" prop="id" />
      <el-table-column label="标题" align="center" prop="title" />
      <el-table-column label="分数" align="center" prop="score" />
      <el-table-column label="类型" align="center" prop="type">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.question_type" :value="scope.row.type" />
        </template>
      </el-table-column>
      <el-table-column label="备注" align="center" prop="remark" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button size="mini" type="text" plan @click="handleUpdate(scope.row)"
            v-hasPermi="['exa:bank:edit']">修改</el-button>
          <el-button size="mini" type="text" plan @click="handleDelete(scope.row)"
            v-hasPermi="['exa:bank:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
      @pagination="getList" />

    <!-- 添加或修改题库管理对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="560px" append-to-body>
      <div style="display: flex; justify-content: space-between;align-items: center;">
        <div style="width: 94px;font-size: 16px; color: #9FA19C;">基础部分</div>
        <el-divider></el-divider>
      </div>

      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <div class="dialog_form">

          <el-row>
            <el-col :span="24">
              <el-form-item label="试题标题" prop="title">
                <el-input v-model="form.title" placeholder="请输入标题" />
              </el-form-item>
            </el-col>
          </el-row>

          <el-row>
            <el-col :span="12">
              <el-form-item label="试题类型" prop="type">
                <el-select v-model="form.type" placeholder="请选择试题类型" :disabled="form.id != null">
                  <el-option v-for="item in testTypeList" :key="item.value" :label="item.label" :value="item.value" />
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>

          <el-row>
            <el-col :span="12">
              <el-form-item label="分数" prop="score">
                <el-input v-model="form.score" placeholder="请输入分数" />
              </el-form-item>
            </el-col>
          </el-row>
        </div>

        <div style="display: flex; justify-content: space-between;align-items: center;">
          <div style="width: 94px;font-size: 16px; color: #9FA19C;">题目内容</div>
          <el-divider></el-divider>
        </div>

        <div class="dialog_form">
          <div style="margin-left: 25px;">
            <el-form-item label="操作">
              <el-button @click="addTest" type="primary" round style="width: 80px;margin-left: 10px;">添加</el-button>
            </el-form-item>
          </div>

          <!-- 单选题 -->
          <el-row v-if="form.type == '1'">
            <div v-for="(item, index) in exaQuestionOptionsList" :key="index">
              <el-col :span="15">
                <el-form-item :label="`选项${String.fromCharCode(65 + index)}：`" prop="content">
                  <el-input v-model="item.content" />
                </el-form-item>
              </el-col>
              <el-col :span="5">
                <div style="margin: 8px 0 0 10px;">
                  <el-switch v-model="item.rorw" active-icon-class="el-icon-check" inactive-icon-class="el-icon-close"
                    active-color="#13ce66" inactive-color="#ff4949" @change="handleSwitchChange(index)" />
                </div>
              </el-col>
              <el-col :span="4">
                <el-button type="danger" @click="removeTest(index)"
                  :disabled="exaQuestionOptionsList.length === 1">删除</el-button>
              </el-col>
            </div>
          </el-row>

          <!-- 多选题 -->
          <el-row v-if="form.type == '2'">
            <div v-for="(item, index) in exaQuestionOptionsList" :key="index">
              <el-col :span="15">
                <el-form-item :label="`选项${String.fromCharCode(65 + index)}：`" prop="content">
                  <el-input v-model="item.content" />
                </el-form-item>
              </el-col>
              <el-col :span="5">
                <div style="margin: 8px 0 0 10px;">
                  <el-switch v-model="item.rorw" active-icon-class="el-icon-check" inactive-icon-class="el-icon-close"
                    active-color="#13ce66" inactive-color="#ff4949" />
                </div>
              </el-col>
              <el-col :span="4">
                <el-button type="danger" @click="removeTest(index)"
                  :disabled="exaQuestionOptionsList.length === 1">删除</el-button>
              </el-col>
            </div>
          </el-row>

          <!-- 判断题 -->
          <el-row v-if="form.type == '3'">
            <div v-for="(item, index) in exaQuestionOptionsList" :key="index">
              <el-col :span="15">
                <el-form-item :label="`选项${String.fromCharCode(65 + index)}：`" prop="content">
                  <el-input v-model="item.content" />
                </el-form-item>
              </el-col>
              <el-col :span="5">
                <div style="margin: 8px 0 0 10px;">
                  <el-switch v-model="item.rorw" active-icon-class="el-icon-check" inactive-icon-class="el-icon-close"
                    active-color="#13ce66" inactive-color="#ff4949" @change="handleSwitchChange(index)" />
                </div>
              </el-col>
              <el-col :span="4">
                <el-button type="danger" @click="removeTest(index)"
                  :disabled="exaQuestionOptionsList.length === 1">删除</el-button>
              </el-col>
            </div>
          </el-row>

          <!-- 简答题 -->
          <el-row v-if="form.type == '4'">

            <el-form-item label="图片" prop="images">
              <image-upload v-model="form.images" />
            </el-form-item>

            <div v-for="(item, index) in exaQuestionOptionsList" :key="index">

              <el-col :span="19">
                <el-form-item label="文本字数" prop="maxString">
                  <el-input type="number" v-model.number="form.maxString" placeholder="输入答题文本的最大字数" :min="1"
                    @change="handleMaxStringChange($event, index)" />
                </el-form-item>
              </el-col>

              <el-col :span="4" style="margin-left: 20px;">
                <el-button type="danger" @click="removeTest(index)">删除</el-button>
              </el-col>

            </div>
          </el-row>
        </div>
      </el-form>

      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listBank, getBank, delBank, addBank, updateBank, saveOrUpdate } from "@/api/exa/bank"
import { listOptions } from "@/api/exa/options"

export default {
  name: "Bank",
  dicts: ['question_type'],
  data() {
    return {
      // 遮罩层
      loading: true,
      loading2: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 题库管理表格数据
      bankList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        title: null,
        score: null,
        type: null,
        createBy: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        title: [{ required: true, message: '请输入试题标题', trigger: 'blur' }],
        score: [{ required: true, message: '请输入分数', trigger: 'blur' }],
        type: [{ required: true, message: '请选择试题类型', trigger: 'change' }],
        // maxString: [{ required: true, message: '请输入最大字数', trigger: 'blur' }],
        // content: [{ required: true, message: '请输入选项内容', trigger: 'blur' }],
      },
      testTypeList: [
        { label: '单选题', value: '1' },
        { label: '多选题', value: '2' },
        { label: '判断题', value: '3' },
        { label: '简答题', value: '4' },
      ],
      value: false, // 用于控制开关状态
      exaQuestionOptionsList: [
        { content: '', rorw: false }
      ],
    }
  },
  created() {
    this.getList()
  },
  methods: {
    /** 查询题库管理列表 */
    getList() {
      this.loading = true
      listBank(this.queryParams).then(response => {
        this.bankList = response.rows
        this.total = response.total
        this.loading = false
      })
    },

    // 添加试题选项
    addTest() {
      if (!this.form.type) return this.$modal.msgWarning("请先选择试题类型")
      this.exaQuestionOptionsList.push({ content: '', rorw: false })
      // 如果form.type为4 则最多只能添加一条
      if (this.form.type === '4' && this.exaQuestionOptionsList.length > 1) {
        this.$modal.msgWarning("简答题只能添加一条选项")
        this.exaQuestionOptionsList.pop() // 删除最后添加的选项
      }
    },

    // 删除试题选项
    removeTest(index) {
      if (this.form.type === '4') {
        this.exaQuestionOptionsList = []
      } else {
        // 其他题型删除选项
        this.exaQuestionOptionsList.splice(index, 1);
      }
    },

    // 单选题切换开关
    handleSwitchChange(currentIndex) {
      // 遍历所有选项，将非当前选中的选项设置为 false
      this.exaQuestionOptionsList.forEach((item, index) => {
        if (index !== currentIndex) {
          item.rorw = false;
        }
      });
    },
    // 取消按钮
    cancel() {
      this.open = false
      this.reset()
    },

    // 表单重置
    reset() {
      this.form = {
        id: null,
        title: null,
        score: null,
        type: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
        remark: null
      }
      this.exaQuestionOptionsList = [{ content: '', rorw: false }]
      this.resetForm("form")
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm")
      this.handleQuery()
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset()
      this.open = true
      this.title = "添加题库管理"
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset()
      const id = row.id || this.ids
      this.loading2 = true
      getBank(id).then(response => {
        console.log(response);

        this.form = response.data
        this.open = true

        // response.data.id
        listOptions({ questionId: response.data.id }).then(res => {
          console.log(res);
          this.loading2 = false

          this.exaQuestionOptionsList = res.rows
        })
        this.title = "修改题库管理"
      })
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          // 检查选项内容是否为空
          const hasEmptyContent = this.exaQuestionOptionsList.some(item => !item.content.trim())
          if (hasEmptyContent) {
            this.$modal.msgWarning("选项内容不能为空")
            return
          }

          const data = {
            exaQuestionBank: {
              ...this.form,
              maxString: parseInt(this.form.maxString)
            },
            exaQuestionOptionsList: this.exaQuestionOptionsList
          }

          if (this.form.id != null) {
            saveOrUpdate(data).then(response => {
              this.$modal.msgSuccess("修改成功")
              this.open = false
              this.reset()
              this.getList()
            })
          } else {
            saveOrUpdate(data).then(response => {
              this.$modal.msgSuccess("新增成功")
              this.open = false
              this.reset()
              this.getList()
            })
          }
        }
      })
    },

    handleMaxStringChange(value, index) {
      const num = parseInt(value);
      if (num <= 0) {
        this.form.maxString = 1;
        this.$message.warning('最小字数不能小于1');
      } else {
        this.form.maxString = num; // 确保存储为数字类型
      }
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids
      this.$modal.confirm('是否确认删除题库管理编号为"' + ids + '"的数据项？').then(function () {
        return delBank(ids)
      }).then(() => {
        this.getList()
        this.$modal.msgSuccess("删除成功")
      }).catch(() => { })
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('exa/bank/export', {
        ...this.queryParams
      }, `bank_${new Date().getTime()}.xlsx`)
    }
  }
}
</script>
